/**
 * Created by wyh911 on 2015/6/24.
 * 练习koa
 */

/**
 * 依赖
 */
var koa = require('koa');
var route = require('koa-route');
var render = require('./routes/render');
var logger = require('koa-logger');
var parse = require('co-body');

var app = koa();

// "database"
var posts = [];

app.use(logger());

/*app.use(function *(next){
    this.body = "各位早上好！这是一个koa的简单例子！";
    this.body = this.request.toJSON();
});*/

//路由中间件
app.use(route.get("/", list));
app.use(route.get("/post/new", add));
app.use(route.get("/post/:id", show));
app.use(route.get("/post", create));
app.use(route.get("/qbao", qbao));//测试react


/**
 * 测试一下react代码
 */
function *qbao(){
    this.body = yield render("qbao");
}

/**
 * post listing
 */
function *list(){
    this.body = yield render("list", {posts:posts});
}

/**
 * show create form
 */
function *add(){
    this.body = yield render('new');
}


/**
 *
 * show post :id
 */
function *show(id){
    var post = posts[id];
    if(!post) this.throw(404, "无效的id");
    this.body = yield render("show", {post: post});
}

/**
 * create a post
 */
function * create(){
    var post = yield parse(this);
    var id = posts.push(post) - 1;
    post.created_at = new Date;
    post.id = id;
    this.redirect("/");
}



app.listen(3000);
console.log("监控端口3000");